const globalData = {
  socketTask: null, // WebSocket 实例
  pongTimer: null,  // 心跳定时器
  userId: null,     // 用户 ID
  pongInterval: 30, // 发送心跳间隔 (秒)
  pongTimeout: 55,  // 心跳超时时间 (秒)
  lastPongTime: null, // 最后一次收到 pong 消息的时间
  listeners: [] // 存放消息回调函数
};

// 初始化 WebSocket 连接
const initWebSocket = (url) => {
  if (globalData.socketTask) {
    console.log("WebSocket 已连接，无需重复连接");
    return;
  }

  console.log("正在连接 WebSocket:", url);
  globalData.userId = uni.getStorageSync('user_id');

  globalData.socketTask = wx.connectSocket({
    url: url,
    header: {
      'content-type': 'application/json'
    },
    success: () => console.log("WebSocket 连接成功"),
    fail: (err) => console.error("WebSocket 连接失败", err)
  });

  // 监听 WebSocket 打开
  globalData.socketTask.onOpen(() => {
    console.log("WebSocket 连接已打开");
    sendTextMessage('login', globalData.userId);
    startPingTimer();
  });

  // 监听消息
  globalData.socketTask.onMessage((event) => {
    console.log(event.data)
    const data = JSON.parse(event.data);

    // 调用所有注册的回调函数
    globalData.listeners.forEach((callback) => {
      if (typeof callback === 'function') {
        callback(data);
      }
    });
  });

  // 监听连接关闭
  globalData.socketTask.onClose(() => {
    console.log("WebSocket 连接关闭");
    clearInterval(globalData.pongTimer);
    globalData.socketTask = null;
  });

  // 监听错误
  globalData.socketTask.onError((err) => {
    console.error("WebSocket 发生错误", err);
  });
};

// 发送消息
const sendTextMessage = (type, user_id, to_user_id = 0, content = '', msg_type = 1, duration = 0, url) => {
  if (!globalData.socketTask || globalData.socketTask.readyState !== 1) {
    console.error("WebSocket 未连接，无法发送消息");
    return;
  }
  const data = JSON.stringify({ type, user_id, to_user_id, content, msg_type, duration, url });
  globalData.socketTask.send({
    data,
    success: () => console.log("消息发送成功:", data),
    fail: (err) => console.error("消息发送失败", err)
  });
};

// 订阅 WebSocket 消息
const onMessage = (callback) => {
  if (typeof callback === 'function') {
    globalData.listeners.push(callback);
  }
};

// 取消订阅 WebSocket 消息
const offMessage = (callback) => {
  globalData.listeners = globalData.listeners.filter((cb) => cb !== callback);
};

// 启动心跳定时器
const startPingTimer = () => {
  globalData.pongTimer = setInterval(() => {
    if (globalData.lastPongTime && (Date.now() - globalData.lastPongTime > globalData.pongTimeout * 1000)) {
      console.error("心跳超时，断开 WebSocket 连接");
      closeWebSocket();
    } else {
      sendTextMessage('pong', globalData.userId);
    }
  }, globalData.pongInterval * 1000);
};

// 关闭 WebSocket
const closeWebSocket = () => {
  if (globalData.socketTask) {
    globalData.socketTask.close();
    globalData.socketTask = null;
    clearInterval(globalData.pongTimer);
    globalData.listeners = []; // 清空所有监听者
  }
};

module.exports = {
  initWebSocket,
  sendTextMessage,
  onMessage,
  offMessage,
  closeWebSocket
};
